#region Using

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;

using Gizmox.WebGUI.Forms;
using TVC.Layout;

#endregion

namespace TVC.Forms
{
    public partial class frmView : Form
    {
        readonly string _strType = "ACC";
        GridLayout layout;
        readonly List<ParamItem> Params = new List<ParamItem>();
        string sErr = "";
        DataTable _dt = null;
        public MainForm MainForm { get; set; }
        //bool flagCheck = false;
        public DataTable DataSource
        {
            get { return _dt; }
            set { _dt = value; }
        }
        public DataRow[] ReturnValues { get; set; }
        public DataRow ReturnValue { get; set; }

        public frmView(MainForm form)
        {
            InitializeComponent();
            MainForm = form;
        }
        public frmView(string type, MainForm form)
        {
            InitializeComponent();
            _strType = type;
            MainForm = form;
        }
        public frmView(GridLayout layout, MainForm form)
        {
            InitializeComponent();
            _strType = layout.Type;
            MainForm = form;
        }
        public frmView(Gizmox.WebGUI.Common.Interfaces.IContext objContext)
            : base(objContext)
        {

        }

        public void SetParams(String strParams)
        {
            string[] arrParams = strParams.Split('&');
            foreach (string param in arrParams)
            {

                string[] value = param.Split('=');
                if (value != null && value.Length >= 2)
                {
                    ParamItem it = new ParamItem(value[0], param.Replace(value[0] + "=", ""));
                    Params.Add(it);
                }
            }
        }
        private void frmView_Load(object sender, EventArgs e)
        {
            if (layout == null) layout = new GridLayout(MainForm.ServerPath + "Resources\\Layout\\", String.Format("{0}Documents\\Layout\\{1}\\", MainForm.ServerPath, MainForm.PODInfo.USER_ID), _strType);
            if (layout.LColumn.Count == 0) dgvList.AutoGenerateColumns = true;

            if (_dt == null)
            {
                
                if (_strType == "Period")
                {
                    int minyear = DateTime.Now.Year - 2;
                    int maxyear = DateTime.Now.Year + 2;

                    DataTable dt = new DataTable();
                    DataColumn[] col = new DataColumn[] { new DataColumn("Code"), new DataColumn("Lookup"), new DataColumn("Description") };
                    dt.Columns.AddRange(col);
                    dt.PrimaryKey = new DataColumn[] { dt.Columns["Code"] };
                    for (int i = minyear; i <= maxyear; i++)
                    {
                        for (int j = 1; j < 13; j++)
                        {
                            DataRow row = dt.NewRow();
                            row["Code"] = i.ToString("0000") + j.ToString("000");
                            row["Lookup"] = i.ToString("0000");
                            row["Description"] = String.Format("{0:000}/{1:0000}", j, i);
                            dt.Rows.Add(row);
                        }
                    }
                    AddSelectColumn(dt);
                    bisView.DataSource = dt;
                }
                else
                {
                    string cate = "";
                    Dictionary<string, string> dic = new Dictionary<string, string>();
                    foreach (ParamItem it in Params)
                    {
                        if (it.Name == "cat" || it.Name == "lookup")
                            cate = it.Value;
                        if (!dic.ContainsKey(it.Name))
                            dic.Add(it.Name, it.Value);
                        else dic[it.Name] = it.Value;
                    }
                    string code = "";
                    if (cate == "")
                        cate = _strType;
                    DataTable dt = MainForm.GetDataSource(cate, ref code, dic, ref sErr);

                    AddSelectColumn(dt);
                    
                    bisView.DataSource = dt;
                }
            }
            else
            {
                AddSelectColumn(_dt);
                bisView.DataSource = _dt;
            }
            SetupDGV();
            MainForm.InitAnalysis(null, dgvList, _strType, _strType, ref sErr);
            if (sErr != "")
                lblErr.Text = sErr;

            
            if (dgvList.TotalPages >= layout.CurrentPage) dgvList.CurrentPage = layout.CurrentPage;

            if (FilterRow != null) bisView.Filter = FilterRow;
        }

        private static void AddSelectColumn(DataTable dt)
        {
            if (dt != null)
            {
                if (!dt.Columns.Contains(MainForm.prefixCol + "Select"))
                {
                    DataColumn col = new DataColumn(MainForm.prefixCol + "Select", typeof(bool));
                    dt.Columns.Add(col);
                    col.SetOrdinal(0);
                }
                else
                    foreach (DataRow row in dt.Rows)
                        row[MainForm.prefixCol + "Select"] = false;
            }
        }

        private void SetupDGV()
        {
            if (layout != null)
            {
                if (layout.LColumn.Count > 0)
                    layout.SetUpDGVWithCheck(dgvList);
                else
                    dgvList.AutoGenerateColumns = true;

                if (layout.Width != 0) this.Width = layout.Width;
                if (layout.Height != 0) this.Height = layout.Height;

                miFilter.Checked = layout.ShowFilterRow;
            }
        }



        private void btnRefresh_Click(object sender, EventArgs e)
        {
FilterRow = "";
            if (_dt == null)
            {
                MainForm.LoadDataTable(_strType);
                DataTable dt = MainForm.GetTable(_strType);
                if (!dt.Columns.Contains(MainForm.prefixCol + "Select"))
                    dt.Columns.Add(new DataColumn(MainForm.prefixCol + "Select", typeof(bool)));
                bisView.DataSource = _dt = dt;
            }


bisView.Filter = "";
            if (layout != null)
            {
                layout.ResetLayout();
                layout.LoadLayout();
                SetupDGV();
            }
            
        }

        private void dgvList_DoubleClick(object sender, EventArgs e)
        {
            btnOK_Click(null, null);
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            if (dgvList.CurrentCell != null)
            {
                List<DataRow> listRows = new List<DataRow>();
                foreach (DataGridViewRow row in dgvList.Rows)
                {
                    if (row.Cells[MainForm.prefixCol + "Select"].Value != null
                        && row.Cells[MainForm.prefixCol + "Select"].Value != DBNull.Value
                        && (bool)row.Cells[MainForm.prefixCol + "Select"].Value == true)
                    {
                        listRows.Add(((DataRowView)row.DataBoundItem).Row);
                    }
                }
                if (listRows.Count > 0)
                    ReturnValues = listRows.ToArray();
                ReturnValue = ((DataRowView)dgvList.CurrentRow.DataBoundItem).Row;
                DialogResult = DialogResult.OK;
                Close();
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void frmView_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (layout != null)
            {
                layout.GetUpDGV(dgvList);
                layout.SaveLayout();
            }
        }

        class ParamItem
        {
            string name = "";
            string value = "";

            public string Name
            {
                get { return name; }
                set { name = value; }
            }
            public string Value
            {
                get { return value; }
                set { this.value = value; }
            }
            public ParamItem(string name, string value)
            {
                this.name = name;
                this.value = value;
            }
        }

        private void dgvList_KeyUp(object objSender, KeyEventArgs objArgs)
        {
            //if (objArgs.KeyCode == Keys.Enter)
            //{
            //    if (dgvList.CurrentCell != null)
            //    {

            //        int max = dgvList.ItemsPerPage * dgvList.CurrentPage;
            //        if (dgvList.CurrentCell.RowIndex == max - 1 && dgvList.CurrentCell.RowIndex == dgvList.Rows.Count - 1)
            //        {
            //            ReturnValue = ((DataRowView)dgvList.CurrentRow.DataBoundItem).Row;
            //            DialogResult = DialogResult.OK;
            //            Close();
            //        }
            //        else
            //        {

            //            ReturnValue = ((DataRowView)dgvList.Rows[dgvList.CurrentCell.RowIndex - 1].DataBoundItem).Row;
            //            DialogResult = DialogResult.OK;
            //            Close();
            //        }
            //    }
            //}
        }

        private void dgvList_MenuClick(object objSource, MenuItemEventArgs objArgs)
        {
            if (objArgs.MenuItem.Tag.ToString().ToUpper() == "ALL")
            {
                objArgs.MenuItem.Checked = !objArgs.MenuItem.Checked;
                for (int i = 0; i < dgvList.Rows.Count; i++)
                {
                    dgvList.Rows[i].Cells[MainForm.prefixCol + "Select"].Value = objArgs.MenuItem.Checked;
                }
            }
            else if (objArgs.MenuItem.Tag.ToString().ToUpper() == "PAGE")
            {
                objArgs.MenuItem.Checked = !objArgs.MenuItem.Checked;
                int firstRow = dgvList.FirstDisplayedScrollingRowIndex;
                int Cout = dgvList.FirstDisplayedScrollingRowIndex + dgvList.ItemsPerPage;
                if (Cout > dgvList.Rows.Count) Cout = dgvList.Rows.Count;
                for (int i = firstRow; i < Cout; i++)
                {
                    dgvList.Rows[i].Cells[MainForm.prefixCol + "Select"].Value = objArgs.MenuItem.Checked;
                }
            }
            else if (objArgs.MenuItem.Tag.ToString().ToUpper() == "FILTER")
            {
                miFilter.Checked = !miFilter.Checked;
                dgvList.ShowFilterRow = miFilter.Checked;
            }
            else if (objArgs.MenuItem.Tag.ToString().ToUpper() == "SAVE")
            {
                if (layout != null)
                {
                    layout.GetUpDGV(dgvList);
                    layout.Width = this.Width;
                    layout.Height = this.Height;

                    layout.SaveLayout();
                }
            }
            else if (objArgs.MenuItem.Tag.ToString().ToUpper() == "RESET")
            {
                if (layout != null) layout.ResetLayout();
            }
        }

        private void dgvList_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (dgvList.CurrentCell != null)
            {
                ReturnValue = ((DataRowView)dgvList.CurrentRow.DataBoundItem).Row;
                DialogResult = DialogResult.OK;
                Close();
            }
        }

        private void bisView_BindingComplete(object sender, BindingCompleteEventArgs e)
        {
            if (layout != null) dgvList.CurrentPage = layout.CurrentPage;
        }

        public string FilterRow { get; set; }
    }
}